using System;

using TrueCode.Core.Diagnostics;

namespace TrueCode.Core
{
	public static class EnumExtensions
	{
		public static TEnum IntToEnum<TEnum>(this int value)
		{
			Type enumType = typeof( TEnum );
			if(! DebugAssert.IsTrue(Enum.IsDefined(enumType, value)))
			{
				var exception = ExceptionHelper.CreateException< TEnum, ArgumentException >(new ArgumentException("value"));
				exception.Data.Add("Enum type", enumType);
				exception.Data.Add("Value", value);
				throw exception;
			}
			try
			{
				return (TEnum)Enum.ToObject(enumType, value);
			}
			catch( ArgumentException exc )
			{
				Exception< TEnum, ArgumentException > exception =
					ExceptionHelper.CreateException< TEnum, ArgumentException >(
						new ArgumentException("Generic parameter must be an enum", "TEnum", exc));
				exception.Data.Add("Enum type", enumType);
				throw exception;
			}
		}
	}
}